package part14;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wcj
 * @Date 2021/5/26 14:29
 * @Version 1.0
 */
public class Part146<T> {

    private Class<T> type;

    public Part146(Class<T> type) {
        this.type = type;
    }

    public List<T> create(int element) {
        List<T> res = new ArrayList<>();
        try {
            for (int i = 0; i < element; i++) {
                res.add(type.newInstance());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return res;
    }

    /**
     * newInstance()这个方法的使用需要类具备一个默认无参构造器
     * 通过子类对象获取基类class,无法使用确切的类型，只能为Object，这相对而言有点受限
     *
     * @param args
     */
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        Part146<CountedInteger> countedIntegerPart146 = new Part146<CountedInteger>(CountedInteger.class);
        System.out.println(countedIntegerPart146.create(15));

        Class<ExtendsInteger> extendsIntegerClass = ExtendsInteger.class;
        ExtendsInteger extendsInteger = extendsIntegerClass.newInstance();
        // 这里就是在继承关系中，明确知道了超类的类型，但是无法使用Class<CountedInteger>,并且newInstance()只能得到Object
        Class<? super ExtendsInteger> superclass = extendsIntegerClass.getSuperclass();
        Object object = superclass.newInstance();
    }
}

class CountedInteger {
    private static long counter;
    private final long id = counter++;

    @Override
    public String toString() {
        return Long.toString(id);
    }
}

class ExtendsInteger extends CountedInteger {
}
